package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.AbstractIdleService;
import com.sun.net.httpserver.HttpServer;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.Executors;

/**
 * 基础 HTTP 服务器示例
 *
 * @author yangyunjiao
 */
public class SimpleHttpService extends AbstractIdleService {
    private HttpServer server;
    private final int port;

    public SimpleHttpService(int port) {
        this.port = port;
    }

    @Override
    protected void startUp() throws Exception {
        System.out.println("Starting HTTP server on port " + port);

        // 创建 HTTP 服务器
        server = HttpServer.create(new InetSocketAddress(port), 0);

        // 添加简单的处理程序
        server.createContext("/", exchange -> {
            String response = "Hello from AbstractIdleService!";
            exchange.sendResponseHeaders(200, response.length());
            exchange.getResponseBody().write(response.getBytes());
            exchange.getResponseBody().close();
        });

        server.createContext("/health", exchange -> {
            String response = "{\"status\":\"healthy\"}";
            exchange.getResponseHeaders().set("Content-Type", "application/json");
            exchange.sendResponseHeaders(200, response.length());
            exchange.getResponseBody().write(response.getBytes());
            exchange.getResponseBody().close();
        });

        server.setExecutor(Executors.newFixedThreadPool(10));
        server.start();

        System.out.println("HTTP server started successfully");
    }

    @Override
    protected void shutDown() throws Exception {
        System.out.println("Stopping HTTP server");
        if (server != null) {
            server.stop(1); // 1秒优雅关闭时间
        }
        System.out.println("HTTP server stopped");
    }

    public static void main(String[] args) throws InterruptedException {
        SimpleHttpService service = new SimpleHttpService(8080);

        // 启动服务
        service.startAsync().awaitRunning();
        System.out.println("Service is running: " + service.isRunning());

        httpRequest();

        // 让服务运行一段时间
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 停止服务
        service.stopAsync().awaitTerminated();
        System.out.println("Service is running: " + service.isRunning());
    }

    private static void httpRequest() {
        Thread httpGet = new Thread(() -> {
            try(HttpClient client = HttpClient.newHttpClient()) {
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create("http://localhost:8080/")) // 请求 URL（含参数）
                        .timeout(java.time.Duration.ofSeconds(10)) // 超时时间
                        .GET() // 指定请求方法（默认就是 GET，可省略）
                        .build();

                HttpResponse<String> response = client.send(
                        request,
                        HttpResponse.BodyHandlers.ofString() // 响应体以 String 接收
                );

                // 4. 打印结果（响应码 + 响应体）
                System.out.println("响应码：" + response.statusCode());
                System.out.println("响应体：" + response.body());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        httpGet.start();
    }
}
